package c.x.jy.bean.event.listener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import c.x.jy.bean.event.WxTemplateMsgEvent;
import c.x.jy.common.templateMsg.Content;
import c.x.jy.common.templateMsg.TemplateMessage;
import c.x.jy.common.utils.HttpUtil;
import c.x.jy.service.config.WechatConfigService;
import c.x.jy.service.utils.wechat.WechatConfig;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class WxTemplateListener {

	/**
	 * 模板消息请求路径
	 */
	private static String TemplateMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	@Autowired
	private WechatConfigService wechatConfigService;
 
	
	@Autowired
	private Environment env;

	@Async
	@EventListener
	public void payServiceSuccess(WxTemplateMsgEvent wxTemplateMsgEvent) {
		Map<String, Object> map = (Map<String, Object>) wxTemplateMsgEvent.getData();
		WechatConfig config = wechatConfigService.getDefultConfing();
		String accesToken = wechatConfigService.getAccessToken(config.getGzhAppId(), config.getGzhAppSecret());
		String url = TemplateMessageUrl.replace("ACCESS_TOKEN", accesToken);
		try {
			HttpUtil.postGeneralUrl(url, generator(map), "utf-8", null);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * {{first.DATA}}
服务单号：{{keyword1.DATA}}
工程师：{{keyword2.DATA}}
联系方式：{{keyword3.DATA}}
服务时间：{{keyword4.DATA}}
{{remark.DATA}}
	 * @param map
	 * @return
	 */

	@SuppressWarnings("unchecked")
	public String generator(Map<String, Object> map) {

		TemplateMessage templateMessage = new TemplateMessage();
		templateMessage.setUrl(env.getProperty("xuanzhu.baseUrl") + env.getProperty("xuanzhu.wechatUrl") + map.get("url").toString());// 跳转地址
		templateMessage.setTouser(map.get("openId").toString());
		templateMessage.setTemplate_id(map.get("templateId").toString());// 模板ID
		List<String> list = (List<String>) map.get("keys");
		// 设置模板标题
		Map<String, Object> tmp = new HashMap<>();
		Content c = new Content();
		c.setValue(list.get(0));
		tmp.put("first", c);
	    c = new Content();
		c.setValue(list.get(1));
		tmp.put("remark", c);
		for (int i = 2; i < list.size(); i++) {
		    c = new Content();
			c.setValue(list.get(i));
			c.setColor(map.containsKey("color") ? map.get("color").toString() : "#FF0000");
			tmp.put("keyword" + (i -1), c);
		}
		templateMessage.setData(tmp);
		return JSON.toJSONString(templateMessage);

	}

}
